package com.utils.commons;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

import com.utils.exceptions.ServiceException;

/**
 * HTTP工具箱
 * 
 */
public final class HttpTookit {
	public static String connectionUrl(String url, String method, Map<String, Object> pramsMap)
			throws IOException {

		String responseMessage = "";
		StringBuffer response = new StringBuffer();
		HttpURLConnection httpConnection = null;
		OutputStreamWriter out = null;
		BufferedReader reader = null;
		try {
			StringBuffer prams = new StringBuffer();
			for (Entry<String, Object> entry : pramsMap.entrySet()) {
				prams.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
			}
			if("GET".equals(method)) {
				url = url+"?" + prams;
			}
			URL urlPost = new URL(url);
			httpConnection = (HttpURLConnection) urlPost.openConnection();
			if("POST".equals(method)) {
				httpConnection.setDoOutput(true);
				httpConnection.setDoInput(true);
			}
			// "POST,GET"
			httpConnection.setRequestMethod(method);
			// 不使用缓存
			httpConnection.setUseCaches(false);
			httpConnection.setInstanceFollowRedirects(true);
			// 设置边界
//			for (Entry<String, List<String>> entry : headers.entrySet()) {
//				if ("HTTP_UDID".equals(entry.getKey()) || "HTTP_APPKEY".equals(entry.getKey())
//						|| "Authorization".equals(entry.getKey())) {
//					httpConnection.setRequestProperty(entry.getKey(), entry.getValue().get(0));
//				}
//			}
			// 意思是正文是urlencoded编码过的form参数
			httpConnection.setRequestProperty("Connection", "Keep-Alive");
			// 设置请求头信息
			httpConnection.setRequestProperty("Charset", "UTF-8");
			// 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的
//			httpConnection.setRequestProperty("Content-Type", "application/json;");
			httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			// 连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
			// 要注意的是connection.getOutputStream会隐含的进行connect。
			// 实际上只是建立了一个与服务器的tcp连接，并没有实际发送http请求。

			httpConnection.connect();
			if("POST".equals(method)) {
				out = new OutputStreamWriter(httpConnection.getOutputStream(), "UTF-8");
				out.write(prams.toString());
				// flush and close
				out.flush();
			}

			int ResponseCode = 0;
			ResponseCode = httpConnection.getResponseCode();
			if (ResponseCode != 200) {
				throw new ServiceException("响应码：" + ResponseCode);
			}
			reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(), "UTF-8"));
			while ((responseMessage = reader.readLine()) != null) {
				response.append(responseMessage);
			}
			return response.toString();
		} catch (IOException e) {
			throw e;
		} finally {
			try {
				if (null != out) {
					out.close();
				}
				if (null != reader) {
					reader.close();
				}
				if (null != httpConnection) {
					httpConnection.disconnect();
				}
			} catch (Exception e2) {
				throw e2;
			}
		}
	}

}